import {useState} from "react";
import {Image, View} from "@tarojs/components";
import Taro, {useLoad} from '@tarojs/taro'
import './index.scss'
import Clock from "../../components/svg/clock.svg";
import Trash2 from "../../components/svg/trash-2.svg";
import {getRequest,deleteRequest} from "../../util/request";
import categoryMap from "../../util/categoryMapping";


export default function Index() {

  const [trainList, setTrainList] = useState<any>([]);

  useLoad(() => {
    console.log('浏览历史页面加载')
    queryList()
  })

  const queryList = () => {
    getRequest('/bsTrain/scan/user',  res=> {
      setTrainList(res.data.recordList.map(item => {
        return {
          id: item.id,
          title: item.title,
          location: item.place,
          date: item.startDate,
          views: item.views,
          category: item.category,
          categoryName: categoryMap[item.category],
          participants: item.participants,
          image: item.cover,
          eventTitle: '',
          thumbnail: item.cover,
          viewedAt: item.scanTime,
          eventId: item.id
        }
      }))
    })
  }

  const gotoPage = (id) => {
    Taro.navigateTo({url: `/pages/traindetail/index?trainId=${id}`});
  }

  const delHistory = (key) => {
    Taro.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (res) {
        if (res.confirm) {
          deleteRequest(`/bsTrain/scan/user/${key}`, res1 => {
            if (res1.success) {
              Taro.showToast({title: '删除成功', icon: 'none'})
              queryList()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  return (
    <View className='list-container'>
      <View className='del-btn' onClick={() => {
        delHistory('all')
      }}
      >清空记录</View>
      {
        trainList.map((item, index) => (
          (
            <View className='doc-card' key={item.id + '_' + index}>
              <Image src={item.thumbnail} className='avatar3' />
              <View className='d-name' onClick={() => gotoPage(item.id)}>{item.title}</View>
              <View className='d-size'>{item.categoryName}</View>
              <View className='d-time'><Image src={Clock} className='avatar1' />{item.viewedAt}</View>
              <Image src={Trash2} className='avatar2 delete-icon' onClick={() => {
                delHistory(item.viewedAt)
              }}
              />
            </View>
          )
        ))
      }
      <View className='page-bottom'></View>
    </View>
  )
}
